//
//  CLAudio.swift
//  clreader
//
//  Created by colin on 2019/4/4.
//  Copyright © 2019 colin. All rights reserved.
//

import UIKit

class CLAudio: Codable {
    var url = "" // 音频播放地址
    
    var cover_url = ""
    var title = ""
    
    var play_time:TimeInterval = 0 // 音频总时间
    var play_count = 0 // 播放量
    
    
    static func audios(objects:[JSONObject]?) -> [CLAudio] {
        if let objects_ = objects {
            
            var audios = [CLAudio]()
            for index in 0 ..< objects_.count {
                let audio = CLAudio()
                let object = objects_[index]
                
                if let goods_url = object["goods_url"] as? String,
                    let baseUrl = URL(string: Router.baseUrl) {
                    audio.url = baseUrl.appendingPathComponent(goods_url).absoluteString
                }
                if let cover_url = object["cover_url"] as? String,
                    let baseUrl = URL(string: Router.baseUrl) {
                    audio.cover_url = baseUrl.appendingPathComponent(cover_url).absoluteString
                }
                if let title = object["title"] as? String {
                    audio.title = title
                }
                if let play_count = object["play_count"] as? Int {
                    audio.play_count = play_count
                }
                
                if let play_time = object["play_time"] as? TimeInterval {
                    audio.play_time = play_time
                }
                
                audios.append(audio)
            }
            return audios
        } else {
            return []
        }
    }
    
}

extension CLAudio : Equatable {
    static func == (lhs: CLAudio, rhs: CLAudio) -> Bool {
        return lhs.url == rhs.url
    }
}

extension Array where Element : CLAudio {
    
    func index(for other:Element) -> Array.Index? {
        let index = self.firstIndex { (item) -> Bool in
            return other == item
        }
        return index
    }
    
}
